﻿using System.Security.Cryptography.X509Certificates;

namespace DoNet.ApiHttpClient
{
    /// <summary>
    /// 该处理器通过ICertSelector决定是否注入证书，实现证书请求与普通请求共存
    /// </summary>
    public class CertBindingHandler : HttpClientHandler
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Options.TryGetValue(new HttpRequestOptionsKey<X509Certificate2>("Certificate"), out var cert))
            {
                ClientCertificateOptions = ClientCertificateOption.Manual;
                ClientCertificates.Clear();
                ClientCertificates.Add(cert);
            }
            return base.SendAsync(request, cancellationToken);
        }
    }
}
